import {
    ArgumentsHost,
    BadRequestException,
    Catch,
    ExceptionFilter,
    HttpCode,
    HttpException,
    HttpStatus,
  } from '@nestjs/common';
  import { Logger } from '../utils/log4js';
  
  //必须实现至ExceptionFilter，固定写法，该接口只有一个catch方法
  //catch方法参数：
  //exception：当前正在处理的异常对象
  //host：传递给原始处理程序的参数的一个包装(Response/Request)的引用
  @Catch(HttpException)
  export class HttpExceptionFilter implements ExceptionFilter<HttpException> {
    catch(exception: HttpException, host: ArgumentsHost) {
      const ctx = host.switchToHttp();
      const response = ctx.getResponse();
      const request = ctx.getRequest();
      const status = exception.getStatus();
      const exceptionRes: any = exception.getResponse(); //获取响应对象
      const { error, message } = exceptionRes;
  
      const logFormat = ` <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
       Request original url: ${request.originalUrl}
       Method: ${request.method}
       IP: ${request.ip}
       Status code: ${status}
       Response: ${JSON.stringify(
         exception,
       )} \n  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
       `;
      Logger.error(logFormat);
      //自定义的异常响应内容
      const msgLog = {
        code: -1,
        timestamp: new Date().toISOString(),
        path: request.url,
        error: `${status >= 500 ? 'Service Error' : 'Client Error'}`,
        message: typeof message == 'string' ? message : JSON.stringify(message),
      };
      // response.status(status).json(msgLog); 修复网关调用时 报错 BUG
      response.status(200).json(msgLog);
    }
  }
  